package com.yungu.swift.api.base.handler;

import com.yungu.swift.api.base.gateway.GatewayHeader;
import com.yungu.swift.api.config.ApplicationConfig;
import com.yungu.swift.api.utils.RsaUtil;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.utils.JsonUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.time.Instant;
import java.util.Date;

import static com.yungu.swift.api.base.ApiErrorEnum.INTERFACE_REPLAY;
import static java.time.temporal.ChronoUnit.MINUTES;

/**
 * 接口防重放
 *
 * @author : cuixiuyin
 * @date : 2019/12/9
 */
public class ReplayHandler extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        Instant instant = new Date(Long.valueOf(request.getHeader(GatewayHeader.noncestr))).toInstant().plus(3, MINUTES);
        if (instant.isBefore(Instant.now())) {
            outPrint(out, JsonUtils.writeJsonStr(ResponseData.buildErrorResponse(INTERFACE_REPLAY.getCode(), INTERFACE_REPLAY.getMsg())));
            return false;
        }
        response.reset();
        return super.preHandle(request, response, handler);
    }

    /**
     * 输出错误
     *
     * @param jsonstr
     */
    private void outPrint(PrintWriter out, String jsonstr) {
        if (ApplicationConfig.SERVER_CONFIG.getSafety().getEncrypt()) {
            out.print(RsaUtil.doUrlAndEncrypt(jsonstr));
        } else {
            out.print(jsonstr);
        }
    }
}
